package com.example.mainexam2022110341

import android.graphics.Color
import android.icu.util.Calendar
import android.os.Bundle
import android.view.MotionEvent
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat

class DayEventsActivity : AppCompatActivity() {

    private val eventsToDelete = mutableListOf<DateEvent>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_day_events)

        // 获取传递过来的数据
        val year = intent.getIntExtra("year",0)
        val month = intent.getIntExtra("month",0)
        val day = intent.getIntExtra("day",0)

        // 设置标题
        val titleTextView: TextView = findViewById(R.id.titleTextView)
        titleTextView.text = "$year-$month-$day 的日程"

        // 设置添加事件按钮
        val addEventImageView: ImageView = findViewById(R.id.addEventImageView)
        addEventImageView.setOnClickListener {
            showAddEventDialog(year.toString(), month.toString(), day.toString())
        }
        addEventImageView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    v.setBackgroundColor(Color.TRANSPARENT) // 松开时恢复背景颜色
                }
            }
            false
        }

        val deleteEventImageView: ImageView = findViewById(R.id.deleteEventImageView)
        deleteEventImageView.setOnClickListener {
            deleteSelectedEvents()
        }
        deleteEventImageView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    v.setBackgroundColor(Color.TRANSPARENT) // 松开时恢复背景颜色
                }
            }
            false
        }


        // 获取该日期的所有事件
        val events = DateEventManager.getEvents(year.toString(), month.toString(), day.toString())

        // 显示事件
        val eventsContainer: LinearLayout = findViewById(R.id.eventsContainer)
        events?.forEach { event ->
            addEventToContainer(event, eventsContainer)
        }

    }

    private fun checkTodayEvents(): Boolean {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR).toString()
        val month = (calendar.get(Calendar.MONTH) + 1).toString()
        val day = calendar.get(Calendar.DAY_OF_MONTH).toString()

        val events = DateEventManager.getEvents(year, month, day)

        return events!=null
    }

    private fun deleteSelectedEvents() {
        eventsToDelete.forEach { event ->
            DateEventManager.clearEvent(event, this)
        }
        // 清空待删除列表
        eventsToDelete.clear()
        // 重新加载事件视图
        val eventsContainer: LinearLayout = findViewById(R.id.eventsContainer)
        eventsContainer.removeAllViews()
        val year = intent.getIntExtra("year", 0).toString()
        val month = intent.getIntExtra("month", 0).toString()
        val day = intent.getIntExtra("day", 0).toString()
        val events = DateEventManager.getEvents(year, month, day)
        events?.forEach { event ->
            addEventToContainer(event, eventsContainer)
        }
    }

    private fun showAddEventDialog(year: String, month: String, day: String) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("添加日程")

        val container = LinearLayout(this)
        container.orientation = LinearLayout.VERTICAL
        container.setPadding(50, 40, 50, 10)

        val typeSpinner = Spinner(this)
        val types = EventType.values().map { it.name }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        typeSpinner.adapter = adapter
        container.addView(typeSpinner)

        val titleInput = EditText(this)
        titleInput.hint = "标题"
        container.addView(titleInput)

        val descriptionInput = EditText(this)
        descriptionInput.hint = "描述"
        container.addView(descriptionInput)

        val yearInput = EditText(this)
        yearInput.hint = "年份"
        yearInput.setText(year)
        //不可更改
        yearInput.isEnabled = false
        container.addView(yearInput)

        val monthInput = EditText(this)
        monthInput.hint = "月份"
        monthInput.setText(month)
        //不可更改
        monthInput.isEnabled = false
        container.addView(monthInput)

        val dayInput = EditText(this)
        dayInput.hint = "日期"
        dayInput.setText(day)
        //不可更改
        dayInput.isEnabled = false
        container.addView(dayInput)

        builder.setView(container)
        builder.setPositiveButton("确定") { dialog, _ ->
            // 处理输入的数据
            val title = titleInput.text.toString()
            val description = descriptionInput.text.toString()
            val type = EventType.valueOf(typeSpinner.selectedItem.toString())
            val dateEvent = DateEvent(
                title = title,
                description = description,
                dateyear = year,
                datemonth = month,
                dateday = day,
                type = type,
            )
            // 添加事件到 DateEventManager
            DateEventManager.addEvent(dateEvent, this)
            // 更新事件视图
            val eventsContainer: LinearLayout = findViewById(R.id.eventsContainer)
            addEventToContainer(dateEvent, eventsContainer)
            dialog.dismiss()
        }
        builder.setNegativeButton("取消") { dialog, _ ->
            dialog.cancel()
        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun addEventToContainer(event: DateEvent, container: LinearLayout) {
        val cardView = CardView(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(16, 16, 16, 16)
            }
            radius = 8f
            cardElevation = 4f

            // 根据事件类型设置背景颜色
            setCardBackgroundColor(
                when (event.type) {
                    EventType.选择日程类型 -> Color.WHITE
                    EventType.工作 -> ContextCompat.getColor(context, R.color.blue)
                    EventType.学习 -> ContextCompat.getColor(context, R.color.green)
                    EventType.约会 -> ContextCompat.getColor(context, R.color.pink)
                    EventType.日常 -> ContextCompat.getColor(context, R.color.yellow)
                    EventType.其他 -> Color.WHITE
                    else -> Color.WHITE
                }
            )
        }

        val eventView = TextView(this).apply {
            text = "标题: ${event.title}\n描述: ${event.description}"
            textSize = 18f
            setPadding(16, 16, 16, 16)
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val eventLayout = LinearLayout(this).apply {
            orientation = LinearLayout.HORIZONTAL
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
        }

        val checkBox = CheckBox(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    eventsToDelete.add(event)
                } else {
                    eventsToDelete.remove(event)
                }
            }
        }

        container.addView(cardView)
        cardView.addView(eventLayout)
        eventLayout.addView(eventView)
        eventLayout.addView(checkBox)
    }

}